﻿'
'   API.vb
'
'   part of WHMCSdotnet (http://whmcsdotnet.wordpress.com)
'
'   Copyright (C) 2009-2011 Mark Castle <markcastle@gmail.com>
'   All rights reserved. 
'   Copyright (C) 2009-2011 Secura Hosting Ltd <code@securahosting.com>.
'   All rights reserved.
' 
'   Redistribution and use in source and binary forms, with or without modification,
'   are permitted provided that the following conditions are met:
' 
'   - Redistributions of source code must  retain  the  above copyright notice, this
'     list of conditions and the following disclaimer.
' 
'   - Redistributions in binary form  must  reproduce the  above  copyright  notice,
'     this list of conditions  and  the  following  disclaimer in  the documentation
'     and/or other materials provided with the distribution.
' 
'   - Neither  the  name  of  Secura Hosting Ltd, Mark Castle  nor the names of  its
'     contributors may be used to endorse or  promote  products  derived  from  this
'     software without specific prior written permission.
' 
'   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
'   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,  BUT  NOT  LIMITED TO, THE IMPLIED
'   WARRANTIES  OF  MERCHANTABILITY   AND  FITNESS  FOR  A  PARTICULAR  PURPOSE  ARE
'   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
'   ANY DIRECT, INDIRECT, INCIDENTAL,  SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL DAMAGES
'   (INCLUDING, BUT NOT LIMITED TO,  PROCUREMENT  OF  SUBSTITUTE  GOODS OR SERVICES;
'   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)  HOWEVER  CAUSED AND ON
'   ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT  LIABILITY,  OR TORT
'   (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING  IN  ANY WAY OUT OF THE USE OF THIS
'   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports Microsoft.VisualBasic
Imports System.Net
Imports System.Diagnostics
Imports System.IO
Imports System.Reflection
Imports System
Imports System.Collections

Namespace Secura.WHMCS

    Public Class API

        ''' <summary>
        ''' A simple structure for passing in WHMCS API Url and Credentials
        ''' </summary>
        ''' <remarks></remarks>
        Public Class Settings
            Public Url As String = ""
            Public Username As String = ""
            Public Password As String = ""
        End Class

        Public Enum ResponseTypes
            XML
            NVP
            JSON
        End Enum

        Public Enum StatusTypes
            Active
            Inactive
            Closed
        End Enum

        ''' <summary>
        ''' Http POST to WHMCS API and get a Response Object
        ''' </summary>
        ''' <param name="WHMCSObject"></param>
        ''' <param name="Settings"></param>
        ''' <param name="HttpUsername"></param>
        ''' <param name="HttpPassword"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function PostRequest(ByVal WHMCSObject As Object, _
                                           ByRef Settings As Secura.WHMCS.API.Settings, _
                                           Optional ByVal HttpUsername As String = "", _
                                           Optional ByVal HttpPassword As String = "") As Secura.WHMCS.Response
            Dim Url As String = Settings.Url.Trim()
            Dim Request As WebRequest = WebRequest.Create(Url)

            ' If the WHMCS API site has been protected using Basic Authentication....
            If HttpUsername <> "" Or HttpPassword <> "" Then
                Dim myCache As New CredentialCache()
                myCache.Add(New Uri(Url), "Basic", _
                            New NetworkCredential(HttpUsername, HttpPassword))

                Request.Credentials = myCache
            End If

            Request.Method = "Post"
            Request.ContentType = "application/x-www-form-urlencoded"

            Dim RequestStream As IO.Stream = Request.GetRequestStream()

            Dim PostDataBytes As Byte() = Nothing

            ' Pass in our **WHMCS** API credentials
            PostData(RequestStream, "Username", Settings.Username.Trim())
            PostData(RequestStream, "Password", MD5(Settings.Password.Trim()))

            ' Pass in each property individually as name/value pairs
            Dim Properties As Hashtable = GetProperties(WHMCSObject)
            For Each Item As DictionaryEntry In Properties
                If Item.Key.ToString().ToLower() = "responsetype" Then Item.Value = Item.Value.ToString.ToLower()
                PostData(RequestStream, Item.Key.ToString(), Item.Value.ToString())
            Next

            RequestStream.Close()

            Dim Reader As New IO.StreamReader(Request.GetResponse().GetResponseStream())

            Dim Xml As String = Reader.ReadToEnd

            Dim Response As New Secura.WHMCS.Response

            Response.Xml = Xml

            Return Response

        End Function

        ''' <summary>
        ''' Helper function for posting name value pairs to an Http Request stream held in memory.
        ''' </summary>
        ''' <param name="RequestStream"></param>
        ''' <param name="Name"></param>
        ''' <param name="Value"></param>
        ''' <remarks></remarks>
        Private Shared Sub PostData(ByRef RequestStream As IO.Stream, ByVal Name As String, ByVal Value As String)
            Dim ASCIIEncoding As New System.Text.ASCIIEncoding
            Dim PostData As Byte() = ASCIIEncoding.GetBytes("&" & Name.ToLower() & "=" & Value)
            RequestStream.Write(PostData, 0, PostData.Length)
        End Sub

        ''' <summary>
        ''' Helper function to produce an MD5 hash of a given string
        ''' </summary>
        ''' <param name="input"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Shared Function MD5(ByVal input As String) As String
            Dim x As New System.Security.Cryptography.MD5CryptoServiceProvider()
            Dim bs As Byte() = System.Text.Encoding.UTF8.GetBytes(input)
            bs = x.ComputeHash(bs)
            Dim s As New System.Text.StringBuilder()
            For Each b As Byte In bs
                s.Append(b.ToString("x2").ToLower())
            Next
            Dim password As String = s.ToString()
            Return password
        End Function

        ' http://www.ogre3d.org/addonforums/viewtopic.php?f=1&t=340
        ' Example Usage: 
        ' Dim MyCamera As Camera = MySceneManager.CreateCamera("MainCam")
        ' ReportProperties(MyCamera)

        Public Shared Function GetProperties(ByVal pObject As Object) As Hashtable

            Dim Properties As New Hashtable

            'This subroutine uses reflection to interogate the properties
            'of this class...

            Dim PInfo As PropertyInfo
            Dim Spaces As Integer
            Dim MaxProperyNameLength As Integer

            ' Output &= "--- Property Report for " & pObject.GetType.ToString & " ---<br/>" & vbCrLf

            'Determine the longest property name (for formatting purposes)...
            For Each PInfo In pObject.GetType.GetProperties()
                If PInfo.Name.Length > MaxProperyNameLength Then
                    MaxProperyNameLength = PInfo.Name.Length
                End If
            Next PInfo

            'By this stage, we know the length (in chars) of the 
            'longest property name.

            For Each PInfo In pObject.GetType.GetProperties()
                Try
                    'Determine the details for this property..
                    Spaces = (MaxProperyNameLength - PInfo.Name.Length) + 1
                    ' Output &= "Property " & PInfo.Name & Space(Spaces) & " Value: " & PInfo.GetValue(pObject, Nothing).ToString & "<br/>" & vbCrLf
                    Properties.Add(PInfo.Name, PInfo.GetValue(pObject, Nothing).ToString)
                Catch ex As Exception
                    ' Output &= "Property " & PInfo.Name & Space(Spaces) & " Value: Unknown<br/>" & vbCrLf
                End Try
            Next PInfo
            ' Output &= "--- End of Property Report for " & pObject.GetType.ToString & " ---<br/>" & vbCrLf
            Return Properties
        End Function     'ReportProperties


        Public Shared Function ReportProperties(ByVal pObject As Object) As String

            Dim Output As String = ""

            'This subroutine uses reflection to interogate the properties
            'of this class...

            Dim PInfo As PropertyInfo
            Dim Spaces As Integer
            Dim MaxProperyNameLength As Integer

            Output &= "--- Property Report for " & pObject.GetType.ToString & " ---<br/>" & vbCrLf

            'Determine the longest property name (for formatting purposes)...
            For Each PInfo In pObject.GetType.GetProperties()
                If PInfo.Name.Length > MaxProperyNameLength Then
                    MaxProperyNameLength = PInfo.Name.Length
                End If
            Next PInfo

            'By this stage, we know the length (in chars) of the 
            'longest property name.

            For Each PInfo In pObject.GetType.GetProperties()
                Try
                    'Determine the details for this property..
                    Spaces = (MaxProperyNameLength - PInfo.Name.Length) + 1
                    Output &= "Property " & PInfo.Name & Space(Spaces) & " Value: " & PInfo.GetValue(pObject, Nothing).ToString & "<br/>" & vbCrLf
                Catch ex As Exception
                    Output &= "Property " & PInfo.Name & Space(Spaces) & " Value: Unknown<br/>" & vbCrLf
                End Try
            Next PInfo
            Output &= "--- End of Property Report for " & pObject.GetType.ToString & " ---<br/>" & vbCrLf
            Return Output
        End Function     'ReportProperties
    End Class
End Namespace